import json
import socket
from collections.abc import MutableMapping


class MessageDict(MutableMapping):
    """
    A dictionary that saves all lane classes and their coords respectively, with a function for serialization.
    """

    def __init__(self, *args, **kwargs):
        self.store = dict()
        self.update(dict(*args, **kwargs))
        self.store['ID'] = '123456'
        self.store['module'] = 'UFLD'
        self.data = dict()
        self.store['data'] = self.data

    def __getitem__(self, key):
        return self.store[self._key_transform(key)]

    def __setitem__(self, key, value):
        self.store[self._key_transform(key)] = value

    def __delitem__(self, key):
        del self.store[self._key_transform(key)]

    def __iter__(self):
        return iter(self.store)

    def __len__(self):
        return len(self.store)

    def __str__(self):
        return json.dumps(self.store)

    @staticmethod
    def _key_transform(key):
        return key

    def add_data(self, key, value) -> None:
        self.data[key] = value

    def send(self, host: str, port: int) -> None:
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        sock.sendto(self.__str__().encode(), (host, port))

    @staticmethod
    def recv(port: int) -> tuple:
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        sock.bind((socket.gethostname(), port))
        data, addr = sock.recvfrom(1024)
        return json.loads(data), addr
